
import docx
from pymongo import MongoClient
import re
import jieba

client = MongoClient('localhost',27017)
db = client.py97
qu_ar = db.qu_ar


def add_info():
    file = docx.Document('D:\words.docx')
    info_list = []
    for i in file.paragraphs:
        str1 = i.text
        info_list.append(str1)
    print(len(info_list))
    i=0
    while i<95648:
        item = info_list[i]
        if '答案' in item:
            s = re.sub(r"(^\d*| )", '', item)
            info = info_list[i-1]
            try:
                if len(info) >7:
                        if info[0] in ['1','2','3','4','5','6','7','8','9']:#判断开头是否为数字编号，这一步为了去除乱码
                            print(item)
                            s1 = re.sub(r"(^\d*| )", '', info)
                            qu_ar.insert_one({'queson':s1,'answers':s})
                            i+=1
                            continue
                        else:
                            i+=1
                            continue
                else:
                    print(item)
                    s1 = re.sub(r"(^\d*| )", '', info_list[i-2])#[i-2]是因为有的问题和答案相隔了一行
                    qu_ar.insert_one({'queson': s1, 'answers': s})
                    i += 1
                    continue
            except Exception as e:
                print(e)
                i += 1
        else:
            i+=1

    qu_ar.create_index([('queson',1)])


def query():
    print('欢迎使用百问百答'.center(50,'*'))
    while True:
        queson_listall = []
        info = input('请输入你要提的问题：').strip()
        seg_list = jieba.cut_for_search(info)
        str_1 = ','.join(seg_list)
        queson_list = str_1.split(',')
        # print(queson_list)
        for i in queson_list:
            find_list = qu_ar.find({'queson':{'$regex':i}})
            for item in find_list:
                queson_listall.append(item['queson'])
        queson_listall = list(set(queson_listall))#给的文档有大部分重复，这一步是去重复
        print('*'*60)
        for i,j in enumerate(queson_listall,1):
            print(i,j)
        print('*'*60)
        num = int(input('请输入你想看的问题题号:').strip())
        n = 0
        for i in qu_ar.find({'queson':queson_listall[num-1]}):
            if n == 0:
                print(i['answers'])
                n+=1
        number = input('是否继续查询信息：(y/n)').strip()
        if number.isdigit():
            print('输入有误，结束搜索')
            break
        elif number.upper() =='Y':
            continue
        elif number.upper() == 'N':
            print('欢迎下次再来')
            break
        else:
            print('输入有误，结束搜索')
            break


if __name__ == '__main__':
    # add_info()
    query()